package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/file")
public class FileController {

    /***
     * 文件上传的控制器方法
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) {
        try {
            //判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在.");
            }

            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new RuntimeException("文件不存在");
            }

            //获取扩展名 xxxxxx.jpg   xxxx.png
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1);//
            System.out.println("ext : "+ ext);

            //获取文件内容,字节数组
            byte[] bytes = file.getBytes();

            //封装上传内容的实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, ext);

            //文件上传
            // storage
            // M00/00/00/rB9He16QF4eAZy7uAABeUTWwNd482..jpg
            String[] results = FastDFSClient.upload(fastDFSFile);
            for (String result : results) {
                System.out.println(result);
            }

            //将上传文件的具体路径获取到,返回到前端页面.
            // group1/M00/22/33/asdfoiuqewrkljqlwekrjl.jpg
            String url = FastDFSClient.getTrackerUrl() + results[0] + "/" + results[1];

            return new Result(true, StatusCode.OK,"文件上传成功",url);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"文件上传失败");
        }
    }

}
